namespace TomatoBreak.Infrastructure
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web.Mvc;

    using Castle.Windsor;

    public class WindsorDependencyResolver : IDependencyResolver
    {
        private readonly IWindsorContainer container;

        public WindsorDependencyResolver(IWindsorContainer container)
        {
            if (container == null)
            {
                throw new ArgumentNullException("container");
            }

            this.container = container;
        }

        public virtual object GetService(Type serviceType)
        {
            // ReSharper disable EmptyGeneralCatchClause
            try
            {
                return container.Resolve(serviceType);
            }
            catch
            {
                // Eat the exception, otherwise asp.net mvc framework will fail
            }

            // ReSharper restore EmptyGeneralCatchClause
            return null;
        }

        public virtual IEnumerable<object> GetServices(Type serviceType)
        {
            // ReSharper disable EmptyGeneralCatchClause
            try
            {
                return container.ResolveAll(serviceType).Cast<object>();
            }
            catch
            {
                // Again eat the exception to keep alive asp.net mvc
            }

            // ReSharper restore EmptyGeneralCatchClause
            return Enumerable.Empty<object>();
        }
    }
}